/*

To use this:

float doubleClickTime = 150;
Input input = new Input(typeof(Game), OnDoubleClick, doubleClickTime);

public void OnDoubleClick(object sender, EventArgs e) {
  // Your code here
}

*/

using System;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;

namespace LEO.Framework
{
    public class Input : GameComponent
    {

        public delegate void DoubleClick(object sender, EventArgs e);
        public event DoubleClick OnDoubleClick;

        public KeyboardState KeyboardState;
        public MouseState MouseState;
        public KeyboardState PreviousKeyboardState;
        public MouseState PreviousMouseState;
        
        public float DoubleClickTime; // In milliseconds
        
        private TimeSpan doubleClickStartTime;

        public Input(Game game, DoubleClick doubleClickDelegate, float doubleClickTime) : base(game) {
            DoubleClickTime = doubleClickTime;
            OnDoubleClick += doubleClickDelegate;
        }

        public override void Update(GameTime gameTime) {
            KeyboardState = Keyboard.GetState();
            MouseState = Mouse.GetState();
            
            doubleClickStartTime += gameTime.ElapsedGameTime;
            if (PreviousMouseState.LeftButton == ButtonState.Released && MouseState.LeftButton == ButtonState.Pressed) {
                CheckDoubleClick(gameTime);
            }

            PreviousKeyboardState = KeyboardState;
            PreviousMouseState = MouseState;

            base.Update(gameTime);
        }

        private void CheckDoubleClick(GameTime gameTime) {
            if ((doubleClickStartTime - gameTime.ElapsedGameTime) < TimeSpan.FromMilliseconds((double)DoubleClickTime)) {
                OnDoubleClick.Invoke(this, EventArgs.Empty);
                doubleClickStartTime = TimeSpan.Zero;
            }
            else {
                doubleClickStartTime = TimeSpan.Zero;
            }
        }
        
    }
}
